package com.luo.d3s.light.jpa.ec.infrastructure.exhandler;

import com.luo.d3s.ext.aop.config.D3sAopProps;
import com.luo.d3s.ext.aop.exception.handler.D3sDefaultExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 业务异常处理扩展实现
 *
 * @author luohq
 * @date 2023-08-03 13:41
 * @see com.luo.d3s.ext.aop.exception.handler.D3sDefaultExceptionHandler
 * @see com.luo.d3s.ext.aop.config.D3sAopAutoConfiguration
 */
@Component
public class BizExceptionHandler extends D3sDefaultExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(BizExceptionHandler.class);

    public BizExceptionHandler(D3sAopProps d3sAopProps) {
        super(d3sAopProps.getException());
    }

    @Override
    protected void prependPutExToHandler() {
        //扩展异常处理逻辑
        this.putExToHandler(EmptyResultDataAccessException.class, this::handleJpa_EmptyResultDataAccessException);
    }

    /**
     * 处理JPA数据不存在异常并返回结果（解决deleteById若数据不存在抛出的异常）
     *
     * @param method    执行方法
     * @param emptyResultDataAccessException 异常
     * @return 响应结果
     * @see org.springframework.data.jpa.repository.support.SimpleJpaRepository.deleteById
     */
    protected Object handleJpa_EmptyResultDataAccessException(Method method, EmptyResultDataAccessException emptyResultDataAccessException) {
        log.error("Handle jpa exception - {}", emptyResultDataAccessException.getMessage());
        return this.wrapSuccessResp(method.getReturnType(), null, "待操作的数据不存在！");
    }
}
